package com.bml.architect.service.impl;

import com.bml.architect.config.DataSourceKey;
import com.bml.architect.config.DynamicDataSourceContextHolder;
import com.bml.architect.entity.Account;
import com.bml.architect.mapper.AccountMapper;
import com.bml.architect.service.AccountService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: baiml
 * @Title: AccountServiceImpl
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description:
 * @date: 2021/5/11 8:47
 */
@Service
public class AccountServiceImpl implements AccountService {
    private Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

    @Autowired
    private AccountMapper accountMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void debit(String userId, int money) {
        logger.info("+++++++++++++++++扣减账户余额");
        DynamicDataSourceContextHolder.setDataSourceKey(DataSourceKey.ACCOUNT);
        logger.info("当前 XID: {}", RootContext.getXID());
        checkAccount(userId, money);
        logger.info("开始扣减用户 {} 余额", userId);
        Integer record = accountMapper.reduceBalance(userId, money);
        logger.info("扣减用户 {} 余额结果:{}", userId, record > 0 ? "操作成功" : "扣减余额失败");
    }

    private void checkAccount(String userId, int money) {
        Account account = accountMapper.selectByUserId(userId);
        if (account == null) {
            throw new RuntimeException("账户信息为空，请确认!");
        }
        Integer accountMoney = account.getMoney();
        if (money > accountMoney) {
            logger.warn("用户 {} 余额不足，当前余额:{}", userId, account.getMoney());
            throw new RuntimeException("余额不足");
        }
    }


}
